package tools

import (
	"crypto/rand"
	"fmt"
	"strconv"
)

// ParseUint 解析无符号整型
func ParseUint(str string) (uint, error) {
	if str == "" {
		return 0, nil
	}
	num, err := strconv.ParseUint(str, 10, 32)
	return uint(num), err
}

// ParseInt 解析有符号整型
func ParseInt(str string) (int, error) {
	if str == "" {
		return 0, nil
	}
	num, err := strconv.ParseInt(str, 10, 32)
	return int(num), err
}

// ParseInt64 解析有符号长整型
func ParseInt64(str string) (int64, error) {
	if str == "" {
		return 0, nil
	}
	num, err := strconv.ParseInt(str, 10, 64)
	return num, err
}

// ParseUint64 解析无符号长整型
func ParseUint64(str string) (uint64, error) {
	if str == "" {
		return 0, nil
	}
	num, err := strconv.ParseUint(str, 10, 64)
	return num, err
}

// RandomStr 生成随机串
func RandomStr(n uint) (string, error) {
	const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	bytes := make([]byte, n)                    // 存储n个随机数
	if _, err := rand.Read(bytes); err != nil { //生成22个随机数
		return "", err // 生成随机串失败
	}
	for i, b := range bytes { //遍历随机数组
		bytes[i] = letters[b%byte(len(letters))] //转换成对应的字符
	}
	return string(bytes), nil
}

func ToString(val any) string {
	return fmt.Sprintf("%v", val)
}
